import React, { Component } from 'react'
import { SyncOutlined } from "@ant-design/icons";
import { Card, List, message } from "antd";
import './Recommend.less'
import ArticleInfo from '../../../types/ArticleInfo';
import { Link } from 'react-router-dom';
import defaultPic from '../../../static/images/default.png'
import Axios from 'axios';
import { queryArticlePicturePath } from '../../../requests/article';
import { getRes } from '../../../configFile';

interface IProps {
    title: React.ReactNode,
    articleList: Array<Pick<ArticleInfo, "articleID" | "articleType" | "title" | "authorID" | "creationTimestamp" | "lastModifiedTimestamp">>
    refresh: () => Promise<void>
}
interface IState {
    coverPics: Map<number, string>
}

export default class ReList extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            coverPics: new Map()
        }
    }

    //获取文章封面
    getCovers = async () => {
        try {
            const coverRes = await Axios.all(this.props.articleList.map(article => queryArticlePicturePath(article.articleID)));
            this.props.articleList.map((article, index) => {
                this.state.coverPics.set(article.articleID, getRes(coverRes[index]).data)
                return null;
            })
            this.setState({ ...this.state })
        } catch (err) {
            message.error("封面获取失败" + err.toString());
        }
    }

    componentDidMount() {
        this.getCovers();
    }

    render() {
        const { title, articleList } = this.props;
        return (
            <Card
                title={<>{title}</>}
                bordered={true}
                headStyle={{ fontSize: '20px' }}
                extra={<div className={'recommendRefreshExtra'} onClick={this.props.refresh}><SyncOutlined />换一批</div>}
            >
                <List
                    dataSource={articleList}
                    renderItem={item => (
                        <div className='reListItem'>
                            <Link to={`/article/${item.articleID}`}>
                                <div className="imgBox">
                                    <img
                                        alt="logo"
                                        src={this.state.coverPics.get(item.articleID) ?
                                            this.state.coverPics.get(item.articleID)
                                            :
                                            defaultPic}
                                        style={{ height: '100%' }}
                                    />
                                </div>
                                <div className="reTitle">
                                    {item.title}
                                </div>
                            </Link>
                        </div>
                    )} />
            </Card>
        )
    }
}